<template>
  <div class="super-admin-dashboard">
    <!-- 系统总览 -->
    <div class="overview-section">
      <div class="section-header">
        <h2 class="section-title">
          <i class="el-icon-data-analysis"></i>
          系统总览
        </h2>
        <div class="header-actions">
          <el-button type="primary" size="small" icon="el-icon-refresh" @click="loadOverview" :loading="loading">刷新数据</el-button>
        </div>
      </div>
      
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="stat-card stat-card-primary">
            <div class="stat-icon">
              <i class="el-icon-office-building"></i>
            </div>
            <div class="stat-content">
              <div class="stat-label">企业总数</div>
              <div class="stat-value">{{ overview.totalEnterprises || 0 }}</div>
              <div class="stat-sub">活跃: {{ overview.activeEnterprises || 0 }}</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card stat-card-success">
            <div class="stat-icon">
              <i class="el-icon-user"></i>
            </div>
            <div class="stat-content">
              <div class="stat-label">用户总数</div>
              <div class="stat-value">{{ overview.totalUsers || 0 }}</div>
              <div class="stat-sub">活跃: {{ overview.activeUsers || 0 }}</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card stat-card-warning">
            <div class="stat-icon">
              <i class="el-icon-s-order"></i>
            </div>
            <div class="stat-content">
              <div class="stat-label">订单总数</div>
              <div class="stat-value">{{ overview.totalOrders || 0 }}</div>
              <div class="stat-sub">成功: {{ overview.successOrders || 0 }}</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card stat-card-danger">
            <div class="stat-icon">
              <i class="el-icon-money"></i>
            </div>
            <div class="stat-content">
              <div class="stat-label">总收入</div>
              <div class="stat-value">¥{{ formatMoney(overview.totalRevenue) }}</div>
              <div class="stat-sub">融资: {{ overview.approvedFinancingRequests || 0 }} 笔</div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 企业管理 -->
    <div class="enterprise-section">
      <div class="section-header">
        <h2 class="section-title">
          <i class="el-icon-office-building"></i>
          企业管理
        </h2>
        <el-button type="primary" icon="el-icon-plus" @click="showCreateDialog">
          创建企业
        </el-button>
      </div>

      <!-- 企业列表 -->
      <el-table
        :data="enterprises"
        v-loading="loading"
        stripe
        style="width: 100%"
        class="mt-table"
      >
        <el-table-column prop="enterprise_id" label="ID" width="80" />
        <el-table-column label="企业信息" min-width="200">
          <template slot-scope="scope">
            <div class="enterprise-info">
              <div class="enterprise-avatar">
                <i class="el-icon-office-building"></i>
              </div>
              <div class="enterprise-detail">
                <div class="enterprise-name">{{ scope.row.enterprise_name }}</div>
                <div class="enterprise-code">{{ scope.row.credit_code || '未填写' }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="订阅计划" width="120">
          <template slot-scope="scope">
            <el-tag :type="getPlanType(scope.row.subscription_plan)" size="small" effect="plain">
              {{ getPlanName(scope.row.subscription_plan) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="用户数" width="100">
          <template slot-scope="scope">
            <span>{{ scope.row.user_count || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="订单数" width="100">
          <template slot-scope="scope">
            <span>{{ scope.row.order_count || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="总收入" width="150">
          <template slot-scope="scope">
            <span class="money-text">¥{{ formatMoney(scope.row.total_revenue) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              active-color="#06C05F"
              inactive-color="#ff4949"
              @change="handleStatusChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="180">
          <template slot-scope="scope">
            {{ formatDate(scope.row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="viewEnterprise(scope.row)">
              查看
            </el-button>
            <el-button size="mini" type="text" @click="editEnterprise(scope.row)">
              编辑
            </el-button>
            <el-button size="mini" type="text" class="text-danger" @click="deleteEnterprise(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 创建/编辑企业对话框 -->
    <el-dialog
      :title="dialogMode === 'create' ? '创建企业' : '编辑企业'"
      :visible.sync="dialogVisible"
      width="600px"
      custom-class="mt-dialog"
    >
      <el-form ref="enterpriseForm" :model="enterpriseForm" :rules="enterpriseRules" label-width="120px">
        <el-form-item label="企业名称" prop="name">
          <el-input v-model="enterpriseForm.name" placeholder="请输入企业名称" />
        </el-form-item>
        <el-form-item label="统一社会信用代码" prop="creditCode">
          <el-input v-model="enterpriseForm.creditCode" placeholder="请输入统一社会信用代码" />
        </el-form-item>
        <el-form-item label="联系人" prop="contactName">
          <el-input v-model="enterpriseForm.contactName" placeholder="请输入联系人姓名" />
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="enterpriseForm.contactPhone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="订阅计划">
          <el-select v-model="enterpriseForm.subscriptionPlan" placeholder="请选择订阅计划">
            <el-option label="免费版" value="FREE" />
            <el-option label="基础版" value="BASIC" />
            <el-option label="专业版" value="PRO" />
            <el-option label="企业版" value="ENTERPRISE" />
          </el-select>
        </el-form-item>
        <el-form-item label="最大用户数">
          <el-input-number v-model="enterpriseForm.maxUsers" :min="1" :max="1000" />
        </el-form-item>
        <el-form-item label="存储配额(MB)">
          <el-input-number v-model="enterpriseForm.storageQuotaMb" :min="100" :max="100000" :step="100" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="enterpriseForm.remark" type="textarea" :rows="3" placeholder="备注信息" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEnterprise" :loading="submitting">
          {{ submitting ? '提交中...' : '确 定' }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import http from '@/api/http'

export default {
  name: 'SuperAdminDashboard',
  data() {
    return {
      superAdmin: {},
      overview: {},
      enterprises: [],
      loading: false,
      dialogVisible: false,
      dialogMode: 'create',
      submitting: false,
      enterpriseForm: {
        name: '',
        creditCode: '',
        contactName: '',
        contactPhone: '',
        subscriptionPlan: 'FREE',
        maxUsers: 10,
        storageQuotaMb: 1024,
        remark: ''
      },
      enterpriseRules: {
        name: [{ required: true, message: '请输入企业名称', trigger: 'blur' }]
      }
    }
  },
  created() {
    // 检查超级管理员登录状态
    const isSuperAdmin = localStorage.getItem('isSuperAdmin')
    if (isSuperAdmin !== 'true') {
      this.$router.push('/super-admin/login')
      return
    }

    const superAdminStr = localStorage.getItem('superAdmin')
    if (superAdminStr) {
      this.superAdmin = JSON.parse(superAdminStr)
    }

    // 设置超级管理员token
    const token = localStorage.getItem('superAdminToken')
    if (token) {
      http.defaults.headers.common['Authorization'] = `Bearer ${token}`
    }

    this.loadOverview()
    this.loadEnterprises()
  },
  methods: {
    async loadOverview() {
      try {
        const { data } = await http.get('/super-admin/enterprises/statistics/overview')
        if (data.code === 0) {
          this.overview = data.data
        }
      } catch (error) {
        console.error('Load overview error:', error)
      }
    },
    async loadEnterprises() {
      this.loading = true
      try {
        const { data } = await http.get('/super-admin/enterprises')
        if (data.code === 0) {
          this.enterprises = data.data
        }
      } catch (error) {
        console.error('Load enterprises error:', error)
        this.$message.error('加载企业列表失败')
      } finally {
        this.loading = false
      }
    },
    showCreateDialog() {
      this.dialogMode = 'create'
      this.enterpriseForm = {
        name: '',
        creditCode: '',
        contactName: '',
        contactPhone: '',
        subscriptionPlan: 'FREE',
        maxUsers: 10,
        storageQuotaMb: 1024,
        remark: ''
      }
      this.dialogVisible = true
    },
    editEnterprise(row) {
      this.dialogMode = 'edit'
      this.enterpriseForm = {
        id: row.enterprise_id,
        name: row.enterprise_name,
        creditCode: row.credit_code,
        contactName: row.contact_name,
        contactPhone: row.contact_phone,
        subscriptionPlan: row.subscription_plan || 'FREE',
        maxUsers: row.max_users || 10,
        storageQuotaMb: row.storage_quota_mb || 1024,
        remark: row.remark || '',
        status: row.status
      }
      this.dialogVisible = true
    },
    async submitEnterprise() {
      try {
        const valid = await this.$refs.enterpriseForm.validate()
        if (!valid) return

        this.submitting = true
        const url = this.dialogMode === 'create'
          ? '/super-admin/enterprises'
          : `/super-admin/enterprises/${this.enterpriseForm.id}`
        const method = this.dialogMode === 'create' ? 'post' : 'put'

        const { data } = await http[method](url, this.enterpriseForm)
        if (data.code === 0) {
          this.$message.success(this.dialogMode === 'create' ? '创建成功' : '更新成功')
          this.dialogVisible = false
          this.loadEnterprises()
          this.loadOverview()
        } else {
          this.$message.error(data.message || '操作失败')
        }
      } catch (error) {
        console.error('Submit enterprise error:', error)
        this.$message.error(error.response?.data?.message || '操作失败')
      } finally {
        this.submitting = false
      }
    },
    deleteEnterprise(row) {
      this.$confirm(`确定要删除企业"${row.enterprise_name}"吗？此操作不可恢复！`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const { data } = await http.delete(`/super-admin/enterprises/${row.enterprise_id}`)
          if (data.code === 0) {
            this.$message.success('删除成功')
            this.loadEnterprises()
            this.loadOverview()
          } else {
            this.$message.error(data.message || '删除失败')
          }
        } catch (error) {
          console.error('Delete enterprise error:', error)
          this.$message.error(error.response?.data?.message || '删除失败')
        }
      }).catch(() => {})
    },
    async handleStatusChange(row) {
       try {
          // 模拟更新状态
          this.$message.success('状态更新成功')
          // 实际应该调用后端接口
       } catch (e) {
         row.status = row.status === 1 ? 0 : 1 // 恢复
         this.$message.error('状态更新失败')
       }
    },
    viewEnterprise(row) {
      this.$router.push(`/super-admin/enterprises/${row.enterprise_id}`)
    },
    formatMoney(value) {
      if (!value) return '0.00'
      return Number(value).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
    },
    formatDate(dateStr) {
      if (!dateStr) return '-'
      return new Date(dateStr).toLocaleString('zh-CN')
    },
    getPlanType(plan) {
      const types = {
        FREE: 'info',
        BASIC: 'success',
        PRO: 'warning',
        ENTERPRISE: 'danger'
      }
      return types[plan] || 'info'
    },
    getPlanName(plan) {
      const names = {
        FREE: '免费版',
        BASIC: '基础版',
        PRO: '专业版',
        ENTERPRISE: '企业版'
      }
      return names[plan] || plan
    }
  }
}
</script>

<style scoped>
.super-admin-dashboard {
  padding: 24px;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  color: var(--text-primary);
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0;
}

.section-title i {
  color: var(--primary-color);
}

/* 统计卡片 - 使用美团配色 */
.stat-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  display: flex;
  align-items: center;
  gap: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
  border: 1px solid var(--border-light);
  height: 120px;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
}

.stat-icon {
  width: 56px;
  height: 56px;
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28px;
  color: #333;
  background: #f5f7fa;
}

.stat-card-primary .stat-icon {
  background: #fff9e6;
  color: #FFD100;
}

.stat-card-success .stat-icon {
  background: #e6f9f0;
  color: #06C05F;
}

.stat-card-warning .stat-icon {
  background: #fff3e0;
  color: #ff9800;
}

.stat-card-danger .stat-icon {
  background: #ffebee;
  color: #ff5757;
}

.stat-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.stat-label {
  font-size: 14px;
  color: var(--text-secondary);
  margin-bottom: 8px;
}

.stat-value {
  font-size: 28px;
  font-weight: 700;
  color: var(--text-primary);
  margin-bottom: 4px;
  font-family: 'DIN Alternate', sans-serif;
}

.stat-sub {
  font-size: 12px;
  color: var(--text-tertiary);
}

/* 企业管理区域 */
.enterprise-section {
  margin-top: 24px;
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.enterprise-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.enterprise-avatar {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  background: var(--bg-primary);
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--primary-dark);
  font-size: 20px;
}

.enterprise-detail {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.enterprise-name {
  font-weight: 600;
  color: var(--text-primary);
  font-size: 14px;
}

.enterprise-code {
  font-size: 12px;
  color: var(--text-tertiary);
}

.money-text {
  color: var(--text-primary);
  font-weight: 600;
  font-family: 'DIN Alternate', sans-serif;
}

.text-danger {
  color: #ff4949;
}

.text-danger:hover {
  color: #ff0000;
}
</style>
